package com.ls.uav_backend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ls.uav_backend.api.verificationCode.EmailService;
import com.ls.uav_backend.api.verificationCode.VerificationCodeService;
import com.ls.uav_backend.exception.BusinessException;
import com.ls.uav_backend.exception.ErrorCode;
import com.ls.uav_backend.exception.ThrowUtils;
import com.ls.uav_backend.mapper.UserMapper;
import com.ls.uav_backend.model.dto.user.UserEditRequest;
import com.ls.uav_backend.model.dto.user.UserForgetPasswordRequest;
import com.ls.uav_backend.model.dto.user.UserQueryRequest;
import com.ls.uav_backend.model.entity.User;
import com.ls.uav_backend.model.enums.UserRoleEnum;
import com.ls.uav_backend.model.vo.user.LoginUserVO;
import com.ls.uav_backend.model.vo.user.UserVO;
import com.ls.uav_backend.service.UserService;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.ls.uav_backend.constant.UserConstant.USER_LOGIN_STATE;

/**
 * @author LinSk
 * @description 针对表【user(用户)】的数据库操作Service实现
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Value("${salt}")
    private String salt;

    @Value("${verification.code.limit-count}")
    private Integer limitCount;

    @Value("${verification.code.expire-minutes}")
    private Integer expireMinutes;

    @Resource
    private EmailService emailService;

    @Resource
    private VerificationCodeService verificationCodeService;

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword) {
        // 1. 校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword, checkPassword),
                ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4,
                ErrorCode.PARAMS_ERROR, "用户账号过短");
        ThrowUtils.throwIf(userPassword.length() < 8 || checkPassword.length() < 8,
                ErrorCode.PARAMS_ERROR, "用户密码过短");
        ThrowUtils.throwIf(!userPassword.equals(checkPassword),
                ErrorCode.PARAMS_ERROR, "两次输入的密码不一致");
        // 2. 检查是否重复
        long count = this.queryChain()
                .eq(User::getUserAccount, userAccount)
                .count();
        ThrowUtils.throwIf(count > 0, ErrorCode.PARAMS_ERROR, "账号重复");
        // 3. 加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 4. 插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setUserName("无名");
        user.setUserRole(UserRoleEnum.USER.getValue());
        boolean saveResult = this.save(user);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "注册失败，数据库错误");
        return user.getId();
    }

    @Override
    public LoginUserVO userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        // 1. 校验
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount, userPassword), ErrorCode.PARAMS_ERROR, "参数为空");
        ThrowUtils.throwIf(userAccount.length() < 4, ErrorCode.PARAMS_ERROR, "账号长度错误");
        ThrowUtils.throwIf(userPassword.length() < 8, ErrorCode.PARAMS_ERROR, "密码长度错误");
        // 2. 加密
        String encryptPassword = getEncryptPassword(userPassword);
        // 查询用户是否存在
        User user = this.queryChain()
                .eq(User::getUserAccount, userAccount)
                .eq(User::getUserPassword, encryptPassword)
                .one();
        // 用户不存在
        if (user == null) {
            log.info("user login failed, userAccount cannot match userPassword");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 3. 记录用户的登录态
        request.getSession().setAttribute(USER_LOGIN_STATE, user);
        return this.getLoginUserVO(user);
    }

    @Override
    public boolean userLogout(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        if (userObj == null) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "未登录");
        }
        // 移除登录态
        request.getSession().removeAttribute(USER_LOGIN_STATE);
        return true;
    }


    @Override
    public User getLoginUser(HttpServletRequest request) {
        // 先判断是否已登录
        Object userObj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        ThrowUtils.throwIf(currentUser == null || currentUser.getId() == null,
                ErrorCode.NOT_LOGIN_ERROR);
        // 从数据库查询（追求性能的话可以注释，直接返回上述结果）
        long userId = currentUser.getId();
        currentUser = this.getById(userId);
        ThrowUtils.throwIf(currentUser == null, ErrorCode.NOT_LOGIN_ERROR);
        return currentUser;
    }


    @Override
    public String getEncryptPassword(String userPassword) {
        // 盐值，混淆密码
        final String SALT = salt;
        return DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());
    }

    @Override
    public Boolean userSendCode(UserForgetPasswordRequest userForgetPasswordRequest) {
        ThrowUtils.throwIf(userForgetPasswordRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userForgetPasswordRequest.getUserAccount();
        String email = userForgetPasswordRequest.getUserEmail();
        if (StrUtil.hasBlank(userAccount, email)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 检查邮箱是否合法
        ThrowUtils.throwIf(!emailService.isValidEmail(email), ErrorCode.PARAMS_ERROR, "邮箱格式不正确");
        try {
            // 判断是否超出限制次数
            verificationCodeService.isExceedLimit(userAccount, email, limitCount);
            // 发验证码
            String code = verificationCodeService.generateCode(6);
            emailService.sendVerificationCode(email, code);
            verificationCodeService.saveCode(userAccount, email, code, expireMinutes);
            verificationCodeService.recordSendCount(userAccount, email);
        } catch (Exception e) {
            log.error("发送验证码失败, 原因：{}", e.getMessage());
            throw new BusinessException(ErrorCode.OPERATION_ERROR, e.getMessage());
        }
        return true;
    }

    @Override
    public Boolean userVerifyCode(UserForgetPasswordRequest userForgetPasswordRequest) {
        ThrowUtils.throwIf(userForgetPasswordRequest == null, ErrorCode.PARAMS_ERROR);
        String userAccount = userForgetPasswordRequest.getUserAccount();
        String email = userForgetPasswordRequest.getUserEmail();
        String code = userForgetPasswordRequest.getUserVerifyCode();
        if (StrUtil.hasBlank(userAccount, email, code)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        // 检查账号和邮箱是否匹配
        User user = this.queryChain()
                .select(User::getUserAccount)
                .select(User::getUserEmail)
                .eq(User::getUserAccount, userAccount)
                .one();
        if (StrUtil.isNotBlank(user.getUserEmail())) {
            ThrowUtils.throwIf(email.equals(user.getUserEmail()), ErrorCode.PARAMS_ERROR, "账号邮箱不一致");
        }
        // 检查验证码是否正确
        verificationCodeService.verifyCode(userAccount, email, code);
        return true;
    }

    @Override
    public Boolean userEditInfo(UserEditRequest userEditRequest) {
        String userAccount = userEditRequest.getUserAccount();
        ThrowUtils.throwIf(StrUtil.hasBlank(userAccount), ErrorCode.PARAMS_ERROR, "参数为空");
        User user = this.queryChain().eq(User::getUserAccount, userAccount).one();
        ThrowUtils.throwIf(user == null, ErrorCode.PARAMS_ERROR, "用户不存在");
        User newEditUser = getNewEditUser(user, userEditRequest);
        boolean res = this.updateById(newEditUser);
        ThrowUtils.throwIf(!res, ErrorCode.OPERATION_ERROR, "修改失败");
        return true;
    }

    @Override
    public LoginUserVO getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVO loginUserVO = new LoginUserVO();
        BeanUtils.copyProperties(user, loginUserVO);
        return loginUserVO;
    }

    @Override
    public UserVO getUserVO(User user) {
        if (user == null) {
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public List<UserVO> getUserVOList(List<User> userList) {
        if (CollUtil.isEmpty(userList)) {
            return new ArrayList<>();
        }
        return userList.stream().map(this::getUserVO).collect(Collectors.toList());
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && UserRoleEnum.ADMIN.getValue().equals(user.getUserRole());
    }

    @Override
    public QueryWrapper getQueryWrapper(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        Long id = userQueryRequest.getId();
        String userAccount = userQueryRequest.getUserAccount();
        String userName = userQueryRequest.getUserName();
        String userProfile = userQueryRequest.getUserProfile();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();
        QueryWrapper queryWrapper = QueryWrapper.create()
                .eq("id", id, ObjUtil.isNotNull(id))
                .eq("userRole", userRole, StrUtil.isNotBlank(userRole))
                .like("userAccount", userAccount, StrUtil.isNotBlank(userAccount))
                .like("userName", userName, StrUtil.isNotBlank(userName))
                .like("userProfile", userProfile, StrUtil.isNotBlank(userProfile));
        if (StrUtil.isNotBlank(sortField)) {
            queryWrapper.orderBy(sortField, sortOrder.equals("ascend"));
        }
        return queryWrapper;
    }

    private User getNewEditUser(User user, UserEditRequest userEditRequest) {
        String userPassword = userEditRequest.getUserPassword();
        String userName = userEditRequest.getUserName();
        String userProfile = userEditRequest.getUserProfile();
        String userEmail = userEditRequest.getUserEmail();
        String userAvatar = userEditRequest.getUserAvatar();
        User newUser = new User();
        BeanUtils.copyProperties(user, newUser);
        newUser.setEditTime(new Date());
        if (StrUtil.isNotBlank(userPassword)) {
            String encryptPassword = getEncryptPassword(userPassword);
            newUser.setUserPassword(encryptPassword);
        }
        if (StrUtil.isNotBlank(userAvatar) && !userAvatar.equals(newUser.getUserAvatar())) {
            newUser.setUserAvatar(userAvatar);
        }
        if (StrUtil.isNotBlank(userName) && !userName.equals(newUser.getUserName())) {
            newUser.setUserName(userName);
        }
        if (StrUtil.isNotBlank(userProfile) && !userProfile.equals(newUser.getUserProfile())) {
            newUser.setUserProfile(userProfile);
        }
        if (StrUtil.isNotBlank(userEmail)) {
            newUser.setUserEmail(userEmail);
        } else {
            newUser.setUserEmail("");
        }
        return newUser;
    }
}




